/**
 * * 省略文本
 * @param text 省略文本
 * @param config 省略配置
 */
export function omitText(
  text: string | null | undefined,
  config: [number, string, number] = [6, "...", 4]
) {
  if (!text) return "----";
  if (text.length <= config[0] + config[2]) return text;
  let res = text.slice(0, config[0]);
  res += config[1];
  res += text.slice(text.length - config[2]);
  return res;
}
/**
 * * query字符串转对象
 * @param url query
 * @returns 结果
 */
export function queryToObj(url: string) {
  const index = url.indexOf("?");
  const obj: { [key: string]: any } = {};
  if (index === -1) return obj;
  const queryStr = url.slice(index + 1);
  const arr = queryStr.split("&");
  for (let item of arr) {
    const keyValue: Array<string> = item.split("=");
    obj[keyValue[0]] = keyValue[1];
  }
  return obj;
}

/**
 * * 字符串转正则
 * @param string 字符串
 * @returns
 */
export function strToRegex(string: string | undefined | null) {
  string ||= "";
  let regexStr = "";
  for (let i = 0; i < string?.length; i++) {
    const char = string[i];
    if (char === "*") {
      // 处理 ** 的情况
      if (string[i + 1] === "*") {
        regexStr += ".*";
        i++; // 跳过下一个 *
      } else {
        regexStr += "[^/]*";
      }
    } else if (char === "?") {
      regexStr += "[^/]";
    } else if (char === "/") {
      regexStr += "\\/";
    } else {
      // 特殊字符需要转义
      regexStr += escapeRegExp(char);
    }
  }
  return new RegExp(regexStr);
}

/**
 * * 将特殊字符转义为正则
 */
export function escapeRegExp(str: string): string {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
